package com.example;

import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/inventory")
@RequiredArgsConstructor
public class InventoryController {

    private final InventoryService inventoryService;

    @PostMapping("/init/{sku}")
    public String initStock(@PathVariable String sku, @RequestParam int totalStock) {
        inventoryService.initStock(sku, totalStock);
        return "库存初始化成功，SKU: " + sku + ", 总库存: " + totalStock;
    }

    @PostMapping("/deduct/{sku}")
    public String deductStock(@PathVariable String sku,
                              @RequestParam String userId,
                              @RequestParam int quantity) {
        
        boolean success = inventoryService.deductStock(sku, userId, quantity);
        if (success) {
            long remaining = inventoryService.getTotalStock(sku);
            return "扣减成功，剩余库存: " + remaining;
        } else {
            return "扣减失败（库存不足或系统繁忙）";
        }
    }

    @GetMapping("/{sku}")
    public long getStock(@PathVariable String sku) {
        return inventoryService.getTotalStock(sku);
    }
}
